<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: yangweijie <yangweijiester@gmail.com> <code-tech.diandian.com>
// +----------------------------------------------------------------------

namespace Help\Model;

use Think\Model;

/**
 * Class HelpModel  帮忙作品
 * @package Help\Model
 * @author:xjw129xjt xjt@ourstu.com
 */
class HelpWorksModel extends Model
{
    protected $tableName = 'help_works';
    protected $attah_table = 'help_works_attach';

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    protected $insertFields = 'help_id,title,detail';
    protected $updateFields = 'help_id,title,detail,status';

    public function addWorks($data)
    {

        $data_a = $data;
        $this->delWorks($data_a['help_id']);
        $data = $this->create($data);
        $res = $this->add($data);
        $data_attach[] = array('help_id' => $data_a['help_id'], 'type' => 'video', 'value' => $data_a['video']);
        $data_attach[] = array('help_id' => $data_a['help_id'], 'type' => 'cover', 'value' => $data_a['cover_id']);
        $ids = explode(',', $data_a['image']);
        foreach ($ids as $v) {
            $data_attach[] = array('help_id' => $data_a['help_id'], 'type' => 'image', 'value' => $v);
        }
        unset($k,$v);
        $result = M($this->attah_table)->addAll($data_attach);
        S('help_work_'.$data_a['help_id'],null);
        return $res;
    }

    public function delWorks($help_id=0){
        $res = $this->where(array('help_id'=>$help_id))->delete();
        M($this->attah_table)->where(array('help_id'=>$help_id))->delete();
        return $res;
    }
    public function getWorks($id)
    {
        $works = S('help_work_' . $id);
        if (empty($works)) {
            $works = $this->where(array('status' => 1, 'help_id' => $id))->find();
            $attach = M($this->attah_table)->where(array('help_id' => $id))->select();

            foreach ($attach as $v) {
                if ($v['type'] == 'cover') {
                    !empty($works) && $works[$v['type']] = $v['value'];
                } elseif($v['type'] == 'video'){
                    !empty($works) && $works[$v['type']][] = $v['value'];
                    preg_match("/(youku.com|youtube.com|qq.com|ku6.com|sohu.com|sina.com.cn|tudou.com|yinyuetai.com)/i", $v['value'], $hosts);
                    $flash =$this->getFlashInfo( $v['value'],$hosts[1]);
                    !empty($works) &&   $works[$v['type']][] =$flash['flash_url'];
                }else {
                    !empty($works) &&  $works[$v['type']][] = $v['value'];
                }
            }
            unset($k,$v);
                     S('help_work_' . $id, $works);
        }
       !empty($works) && $works['help'] = D('Help/Help')->getHelp($id);
       !empty($works) && $works['comment'] = D('Addons://ThreeWords/ThreeWordsComment')->getCount(array('model'=>'help_works','row_id'=>$works['help_id']));
        return $works;
    }

    public function getWorkList($map=''){
        $list = $this->where($map)->field('help_id')->select();
        $ids = getSubByKey($list,'help_id');
        $lists = array();
        foreach($ids as $v){
            $lists[] =  $this->getWorks($v);
        }
        unset($k,$v);
        return $lists;
    }
    public function getFlashInfo($link, $host)
    {

        $return = '';
        if (extension_loaded("zlib")) {
            $content = file_get_contents("compress.zlib://" . $link); //获取
        }

        if (!$content)
            $content = file_get_contents($link);
        //有些站点无法获取

        if ('youku.com' == $host) {
            // 2012/3/7 修复优酷链接图片的获取
            preg_match('/http:\/\/profile\.live\.com\/badge\/\?[^"]+/i', $content, $share_url);
            preg_match('/id\_(.+)\.html/', $share_url[0], $flashvar);
            preg_match('/screenshot=([^"&]+)/', $share_url[0], $img);
            preg_match('/title=([^"&]+)/', $share_url[0], $title);
            if (!empty($title[1])) {
                $title[1] = urldecode($title[1]);
            } else {
                preg_match("/<title>(.*?)<\/title>/i", $content, $title);
            }
            $img[1] = str_ireplace('ykimg.com/0', 'ykimg.com/1', $img[1]);
            $flash_url = 'http://player.youku.com/player.php/sid/' . $flashvar[1] . '/v.swf';
        } elseif ('ku6.com' == $host) {
            // 2012/3/7 修复ku6链接和图片抓去
            preg_match("/\/([\w\-\.]+)\.html/", $link, $flashvar);
            //preg_match("/<span class=\"s_pic\">(.*?)<\/span>/i",$content,$img);
            preg_match("/cover: \"(.+?)\"/i", $content, $img);
            preg_match("/<title>(.*?)<\/title>/i", $content, $title);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = 'http://player.ku6.com/refer/' . $flashvar[1] . '/v.swf';
        } elseif ('tudou.com' == $host && strpos($link, 'www.tudou.com/albumplay') !== false) {
            preg_match("/albumplay\/([\w\-\.]+)\//", $link, $flashvar);
            preg_match("/<title>(.*?)<\/title>/i", $content, $title);
            preg_match("/pic: \"(.+?)\"/i", $content, $img);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = 'http://www.tudou.com/a/' . $flashvar[1] . '/&autoPlay=true/v.swf';
        } elseif ('tudou.com' == $host && strpos($link, 'www.tudou.com/programs') !== false) {
            //dump(auto_charset($content,'GBK','UTF8'));
            preg_match("/programs\/view\/([\w\-\.]+)\//", $link, $flashvar);
            preg_match("/<title>(.*?)<\/title>/i", $content, $title);
            preg_match("/pic: \'(.+?)\'/i", $content, $img);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = 'http://www.tudou.com/v/' . $flashvar[1] . '/&autoPlay=true/v.swf';
        } elseif ('tudou.com' == $host && strpos($link, 'www.tudou.com/listplay') !== false) {
            //dump(auto_charset($content,'GBK','UTF8'));
            preg_match("/listplay\/([\w\-\.]+)\//", $link, $flashvar);
            preg_match('/<title>([^<>]*)<\/title>/', $content, $title);
            preg_match("/pic:\"(.+?)\"/i", $content, $img);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = 'http://www.tudou.com/l/' . $flashvar[1] . '/&autoPlay=true/v.swf';
        } elseif ('tudou.com' == $host && strpos($link, 'douwan.tudou.com') !== false) {
            //dump(auto_charset($content,'GBK','UTF8'));
            preg_match("/code=([\w\-\.]+)$/", $link, $flashvar);
            preg_match("/title\":\"(.+?)\"/i", $content, $title);
            preg_match("/itempic\":\"(.+?)\"/i", $content, $img);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = 'http://www.tudou.com/v/' . $flashvar[1] . '/&autoPlay=true/v.swf';
        } elseif ('youtube.com' == $host) {
            preg_match('/http:\/\/www.youtube.com\/watch\?v=([^\/&]+)&?/i', $link, $flashvar);
            preg_match("/<link itemprop=\"thumbnailUrl\" href=\"(.+?)\">/i", $content, $img);
            preg_match('/<title>([^<>]*)<\/title>/', $content, $title);
            $flash_url = 'http://www.youtube.com/embed/' . $FLASHVAR[1];
        } elseif ('sohu.com' == $host) {
            preg_match("/og:videosrc\" content=\"(.+?)\"/i", $content, $flashvar);
            preg_match("/og:title\" content=\"(.+?)\"/i", $content, $title);
            preg_match("/og:image\" content=\"(.+?)\"/i", $content, $img);
            $title[1] = iconv("GBK", "UTF-8", $title[1]);
            $flash_url = $flashvar[1];
        } elseif ('qq.com' == $host) {
            preg_match("/vid:\"(.+?)\",/i", $content, $flashvar);
            preg_match('/itemprop=\"image\" content=\"(.+?)\"/i', $content, $img);
            preg_match('/<title>([^<>]*)<\/title>/', $content, $title);
            $flash_url = 'http://static.video.qq.com/TPout.swf?vid=' . $flashvar[1] . '&auto=1';
        } elseif ('sina.com.cn' == $host) {
            preg_match("/swfOutsideUrl:\'(.+?)\'/i", $content, $flashvar);
            preg_match("/pic\:[ ]*\'(.*?)\'/i", $content, $img);
            preg_match('/<title>([^<>]*)<\/title>/', $content, $title);
            $flash_url = $flashvar[1];

        } elseif ('yinyuetai.com' == $host) {
            preg_match("/video\/([\w\-]+)$/", $link, $flashvar);
            preg_match("/<meta property=\"og:image\" content=\"(.*)\"\/>/i", $content, $img);
            preg_match('/<title>([^<>]*)<\/title>/', $content, $title);
            $flash_url = 'http://player.yinyuetai.com/video/player/' . $flashvar[1] . '/v_0.swf';
        }
        $return['title'] = op_t($title[1]);
        $return['flash_url'] = op_t($flash_url);
        $return['image_url'] = op_t($img[1]);
        return $return;
    }
    //zzl start

    public function getWorkLists($map='',$page=1,&$totalCount){
        $list = $this->where($map)->field('help_id')->page($page,50)->select();
        $totalCount=$this->where($map)->count();
        $ids = getSubByKey($list,'help_id');
        $lists = array();
        foreach($ids as $v){
            $lists[] =  $this->getWorks($v);
        }
        unset($k,$v);
        return $lists;
    }
    public function getWorkIds($map='',&$totalCount){
        $list = $this->where($map)->field('help_id')->select();
        $totalCount=$this->where($map)->count();
        $ids = getSubByKey($list,'help_id');

        return $ids;
    }
    /**通过用户id获取发布的作品
     * @param array $uids
     * @param array $recommendIds
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getWorkListByUids($uids=array(),$page=1,&$totalCount,$recommendIds=array()){
        if(is_array($recommendIds)&&count($recommendIds)){
            $productIds=$this->getWorkIds(array('help_id'=>array('not in',$recommendIds),'uid'=>array('in',$uids)),$count);//排除推荐的作品，的id
            $totalCount=$count+count($recommendIds);
            if(is_array($productIds)){
                $recommendIds=array_merge($recommendIds,$productIds);
            }
            $productIds=array_slice($recommendIds,($page-1)*50,50);
            $workList = array();
            foreach($productIds as $v){
                $workList[] =  $this->getWorks($v);
            }
            unset($k,$v);
        }else{
            $helpIds=D('Help/Help')->getIds(array('uid'=>array('in',$uids)));
            $workList=array();
            if($helpIds){
                $workList=$this->getWorkLists(array('help_id'=>array('in',$helpIds)),$page,$totalCount);
            }
        }
        return $workList;
    }
}